package com.example.agricultural_big_data.intercepter;

import com.example.agricultural_big_data.util.LoginRequired;
import com.example.agricultural_big_data.util.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * @author susu
 * @Description: 用户拦截
 * @date 2021/1/3111:03
 */
public class AuthenticationInterceptor implements HandlerInterceptor {
    @Autowired
    RedisUtil redisUtil;
    private static final Logger LOGGER = LoggerFactory.getLogger(AuthenticationInterceptor.class);
    //定义请求头里面的字段名
    private static final String AUTHORIZATION = "Authorization";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            LOGGER.info("没有映射到方法，则无需检查直接通过");
            return true;
        }
        HandlerMethod heHandlerMethod = (HandlerMethod) handler;
        Method method = heHandlerMethod.getMethod();

        LoginRequired loginRequired = method.getAnnotation(LoginRequired.class);
        //有LoginRequired注解，不需要认证
        if (loginRequired != null) {
            return true;
        }
            boolean flag = redisUtil.hasKey("token");
            if (flag) {
                return true;
            }
        return  false;
    }


    /**
     * 实现跨域
     * @param request
     * @param response
     * @param message
     */
    @SuppressWarnings("unused")
    private void setHeader(HttpServletRequest request, HttpServletResponse response, String message) {
        try {
            //跨域的header设置
            response.setHeader("Access-control-Allow-Origin", request.getHeader("Origin"));
            response.setHeader("Access-Control-Allow-Methods", request.getMethod());
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Headers", request.getHeader("Access-Control-Request-Headers"));
            //防止乱码，适用于传输JSON数据
            response.setHeader("Content-Type", "application/json;charset=UTF-8");
            response.getWriter().write(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
